#include <iostream>
#include <queue>
#include <unordered_map>

using namespace std;

string aim = "123804765";
unordered_map<string, int> mp;
string s;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};

void bfs()
{
	queue<string> q;
	q.push(s);
	mp[s] = 0;
	while(q.size())
	{
		auto t = q.front(); q.pop();
		int j = 0;
		while(t[j] != '0') j++;
		int x = j / 3;
		int y = j % 3;
		for(int k = 0; k < 4; k++)
		{
			int a = x + dx[k];
			int b = y + dy[k];
			if(a < 0 || a > 2 || b < 0 || b > 2) continue;
			string tmp = t;
			int pos = a * 3 + b;
			swap(tmp[j], tmp[pos]);
			if(mp.count(tmp)) continue;
			mp[tmp] = mp[t] + 1;
			q.push(tmp);
			if(tmp == aim) return;
		}
	}
}

int main()
{
	cin >> s;
	bfs();
	cout << mp[aim] << endl;
	return 0;
}
